package com.xiaotu.code.util;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * 
 * 自定义一个响应结果包装器，将在这里提供一个基于内存的输出器来存储所有
 * 
 * 返回给客户端的原始HTML代码.
 * 
 * @author lee
 */

public class MyResponseWrapper extends HttpServletResponseWrapper {
	private PrintWriter cacheWriter;
	private CharArrayWriter bufferWriter;// 用于保存截获的jsp内容
	public MyResponseWrapper(HttpServletResponse response) {
		super(response);
		bufferWriter = new CharArrayWriter();
		// 这个是包装PrintWriter的，让所有结果通过这个PrintWriter写入到bufferedWriter中
		cacheWriter = new PrintWriter(bufferWriter);
	}

	/**
	 * 
	 *当一个继承了HttpServletResponseWrapper的包装器复写了getWriter()方法时
	 * 
	 *tomcat会把响应的内容塞入自定义的PrintWriter(cacheWriter)中
	 */

	@Override
	public PrintWriter getWriter() throws IOException {
		return cacheWriter;
	}

	/**
	 * 
	 * 获取原始的HTML页面内容.
	 * 
	 * @return
	 */

	public String getResult() {
		return bufferWriter.toString();
	}

}
